<template>
	<div class="dashboard-editor-container main-conent-minheight">
		<div class="main-header">
			<el-row :gutter="10">
				<el-col :sm="12" :md="12" :lg="12">
					<el-card class="box-card" shadow="never" style="height: 510px;">
						<div slot="header" class="clearfix">
							<span class="title">设备维护</span>
						</div>
						<div class="radioClass">
							<div style="margin-bottom: 20px;margin-top: 20px;">
								<div style="font-size: 14px;margin-bottom: 10px;">
									系统升级将会导致原有系统,文件和一些配置被自动升级，建议您升级系统前做好数据备份，升级过程中请勿断电
								</div>
								<div style="display: inline-block;width: 100%;text-align: right;">
									<el-upload class="upload-demo" action :ref="'uploads' + 0" :on-change="handleChange()"
										:show-file-list=false :http-request="upgradeClick" :on-exceed="handleExceeds" :limit="1">
										<el-tooltip class="item" effect="dark" content="系统升级" placement="top">
											<svg-icon icon-class="系统升级"  @click="checkBeforeClick"
												style="font-size: 24px;cursor: pointer;" />
										</el-tooltip>
									</el-upload>
								</div>
							</div>
							<div style="margin-bottom: 20px;">
								<div style="font-size: 14px;">
									请下载代理采集工具并在终端安装以采集扩展日志数据；同时安装RemoteCtrl工具以配置远程控制组件。
								</div>
								<div style="display: inline-block;width: 100%;text-align: right;margin-bottom: 10px;margin-top:5px;">
									<el-tooltip class="item" effect="dark" content="客户端日志列表" placement="top">
										<svg-icon icon-class="列表" @click="openClientLogs()"
											style="font-size: 24px;margin-right: 10px;cursor: pointer;" />
									</el-tooltip>
									<el-tooltip class="item" effect="dark" content="下载Windows客户端" placement="top">
										<svg-icon icon-class="win" @click="downloadTool(FileName)"
											style="font-size: 24px;margin-right: 10px;cursor: pointer;" />
									</el-tooltip>
									<el-tooltip class="item" effect="dark" content="下载远程控制组件" placement="top">
										<svg-icon icon-class="远程控制" @click="downloadTool('RemoteCtrl.zip')"
											style="font-size: 24px;margin-right: 10px;cursor: pointer;" />
									</el-tooltip>
									<el-tooltip class="item" effect="dark" content="下载大屏APP" placement="top">
										<svg-icon icon-class="远程控制" @click="downloadTool('大屏APP.apk')"
											style="font-size: 24px;cursor: pointer;" />
									</el-tooltip>
									<!-- <el-button type="primary" @click="openClientLogs()">客户端日志列表</el-button> -->
									<!-- <el-button type="primary" @click="downloadTool('EDAMPClient.exe')">下载Windows客户端</el-button> -->
									<!-- <el-button  type="primary" @click="downloadTool()">下载Mac客户端</el-button> -->
									<!-- <el-button  type="primary" @click="downloadTool()">下载Linux(ubt)客户端</el-button> -->
									<!-- <el-button type="primary" @click="downloadTool('RemoteCtrl.zip')">下载远程控制组件</el-button> -->
									<!-- <el-button type="primary" @click="downloadTool('大屏APP.apk')">下载大屏APP</el-button> -->
								</div>
							</div>
							<el-dialog top="5vh" :close-on-click-modal="false" :close-on-press-escape=false title="客户端日志列表"
								:visible.sync="dialogVisible" @close="dialogVisible = false" v-el-drag-dialog width="1000px">
								<el-input v-model="DeviceUUID" placeholder="请输入资产名称进行筛选，支持模糊匹配" @input="DeviceUUIDChange"
									style="margin-bottom: 10px;"></el-input>
								<el-table stripe border :data="tableData" row-key="index" height="520"
									style="width: 100%; margin-top: 5px;">
									<el-table-column label="序号" width="60" type="index"></el-table-column>
									<el-table-column label="文件名称" show-overflow-tooltip prop="FileName"></el-table-column>
									<el-table-column label="文件大小" show-overflow-tooltip prop="FileSize" width="180">
										<template slot-scope="{row}">
											<span>{{ formatBytes(row.FileSize) }}</span>
										</template>
									</el-table-column>
									<el-table-column label="修改时间" show-overflow-tooltip prop="Timestamp" width="180">
										<template slot-scope="{row}">
											<span>{{ parseTime(row.Timestamp) }}</span>
										</template>
									</el-table-column>
									<el-table-column label="操作" width="180px">
										<template slot-scope="scope">
											<el-button size="mini" type="primary"
												@click="tableDownloadClick(scope.row, scope.$index)">下载</el-button>
											<el-button size="mini" type="danger"
												@click="tableDeleteClick(scope.row, scope.$index)">删除</el-button>
										</template>
									</el-table-column>
								</el-table>
								<el-divider></el-divider>
								<span slot="footer" class="dialog-footer">
									<el-button type="info" @click="dialogVisible = false;">关 闭</el-button>
								</span>
							</el-dialog>
							<div style="margin-bottom: 20px;">
								<div style="font-size: 14px;">
									设备重启将导致桌面管理系统短时间失效
								</div>
								<div style="display: inline-block;width: 100%;text-align: right;">
									<el-tooltip class="item" effect="dark" content="安全关机" placement="top">
										<svg-icon icon-class="安全关机" @click="operationClick(2)"
											style="font-size: 30px;cursor: pointer;margin-right: 10px;" />
									</el-tooltip>
									<el-tooltip class="item" effect="dark" content="重启设备" placement="top">
										<svg-icon icon-class="重启设备" @click="operationClick(1)"
											style="font-size: 30px;margin-bottom:3px;cursor: pointer;" />
									</el-tooltip>
									<!-- <el-button type="primary" @click="operationClick(2)">安全关机</el-button>
									<el-button type="primary" @click="operationClick(1)">重启设备</el-button> -->
								</div>
							</div>
							<div style="margin-bottom: 20px;">
								<div style="display: inline-block;font-size: 14px;margin-bottom: 10px;">
									如果您是厂商运维人员，在某些特定情况下，您可以通过申请维护并将形成的申请码发给我们，审核后可以进入后台。
								</div>
								<div style="margin-bottom: 10px;">
									<span
										style="width: 280px;display: inline-block;text-align: right;font-size: 14px;">点击申请维护按钮获取申请码：</span>
									<el-input v-model="input1" style="width:calc(100% - 300px);" size="small" ref="inputRef">
										<el-button slot="append" icon="el-icon-document-copy" @click="copy" title="复制申请码"></el-button>
									</el-input>
								</div>
								<div style="margin-bottom: 10px;">
									<span
										style="width: 280px;display: inline-block;text-align: right;font-size: 14px;">输入厂商提供的维护码，点击开始维护：</span><el-input
										v-model="input2" style="width:calc(100% - 300px);" size="small"></el-input>
								</div>
								<div style="display: flex;align-items: center;justify-content: flex-end; width: 100%;">
									<el-tooltip class="item" effect="dark" content="申请维护" placement="top">
										<svg-icon icon-class="申请维护" @click="ApplySSHMaint()"
											style="font-size: 30px;margin-right:10px;cursor: pointer;" />
									</el-tooltip>
									<el-tooltip class="item" effect="dark" content="开启维护" placement="top">
										<svg-icon icon-class="开启维护" @click="StartSSHMaint()"
											style="font-size: 30px;margin-right:10px;margin-bottom:3px;cursor: pointer;" />
									</el-tooltip>
									<el-tooltip class="item" effect="dark" content="结束维护" placement="top">
										<svg-icon icon-class="结束维护" @click="StopSSHMaint()" style="font-size: 30px;cursor: pointer;" />
									</el-tooltip>
									<!-- <el-button @click="ApplySSHMaint()" type="primary">申请维护</el-button>
									<el-button @click="StartSSHMaint()" type="primary">开启维护</el-button>
									<el-button @click="StopSSHMaint()" type="primary">结束维护</el-button> -->
								</div>
							</div>
						</div>
					</el-card>
				</el-col>
				<el-col :sm="12" :md="12" :lg="12">
					<el-card class="box-card" shadow="never" style="height: 510px;">
						<div slot="header" class="clearfix">
							<span class="title">备份恢复</span>
						</div>
						<div style="margin-bottom: 30px;margin-top: 20px;">
							<span style="font-size: 14px;">
								配置备份将会对系统关键配置数据进行备份，建议您定期执行备份。备份后的数据可以用于系统恢复。
							</span>
							<div style="width: 100%;margin-top:10px;text-align: right;">
								<el-tooltip class="item" effect="dark" content="配置备份" placement="top">
									<svg-icon icon-class="配置备份" @click="recoverClick(1)" style="font-size: 30px;cursor: pointer;" />
								</el-tooltip>
								<!-- <el-button type="primary" @click="recoverClick(1)">配置备份</el-button> -->
							</div>
						</div>
						<div style="margin-bottom: 20px;">
							<span style="font-size: 14px;">
								可以使用历史备份配置进行系统恢复，系统恢复将导致当前所有配置丢失，请谨执行。
							</span>
							<div style="width: 100%;margin-top:10px;text-align: right;">
								<el-upload ref="upload" class="upload-demos" action='#' :on-change="onChange"
									:on-preview="handlePreview" :on-remove="handleRemove" :before-remove="beforeRemove"
									:show-file-list="false" :auto-upload="false" multiple :limit="1" :on-exceed="handleExceed"
									:file-list="fileList">
									<el-tooltip class="item" effect="dark" content="配置恢复" placement="top">
										<svg-icon icon-class="配置恢复" style="font-size: 30px;cursor: pointer;"  @click="checkBeforeClick2"/>
									</el-tooltip>
									<!-- <el-button type="primary">配置恢复</el-button> -->
								</el-upload>
							</div>
						</div>
						<div style="margin-bottom: 20px;">
							<span style="font-size: 14px;">
								恢复出厂设置将导致当前所有配置丢失，请谨慎执行。<span style="color: #F56C6C;">（恢复出厂设置时自动删除所有日志数据）</span>
								<!-- <el-checkbox v-model="checked">恢复出厂设置时自动删除所有日志数据</el-checkbox> -->
							</span>
							<div style="width: 100%;margin-top:10px;text-align: right;">
								<el-tooltip class="item" effect="dark" content="恢复出厂" placement="top">
									<svg-icon icon-class="恢复出厂" @click="recoverClick(4)" style="font-size: 30px;cursor: pointer;" />
								</el-tooltip>
								<!-- <el-button type="primary" @click="recoverClick(4)">恢复出厂</el-button> -->
							</div>
						</div>
						<!-- <div class="radioClass" style="margin-bottom:100px">
                            
                                <el-radio v-model="radio" :label="1">备份系统配置</el-radio>
                                <div style="display:flex;align-items: baseline;">
                                    <el-radio v-model="radio" style="margin-right:10px" :label="2">恢复系统配置</el-radio>
                                    <el-upload
                                        v-if="radio === 2"
                                        class="upload-demos"
                                        style="margin-right:30px"
                                        action='#'
                                        :on-change="onChange"
                                        :on-preview="handlePreview"
                                        :on-remove="handleRemove"
                                        :before-remove="beforeRemove"
                                        :auto-upload="false"
                                        multiple
                                        :limit="1"
                                        :on-exceed="handleExceed"
                                        :file-list="fileList">
                                        <el-button size="small" type="primary">上传文件</el-button>
                                    </el-upload>
                                </div>
                                <el-radio v-model="radio" :label="3">恢复出厂配置</el-radio>
                                <el-radio v-model="radio" :label="4">恢复出厂配置并删除所有数据</el-radio>
                                
                            
                        </div>
                        
                        <div>
                        </div>
                            <el-button style="float: right;bottom: 20px; " v-if="radio != 2" type="primary" @click="recoverClick">立即生效</el-button> -->

					</el-card>

				</el-col>
			</el-row>
			<el-row :gutter="10">
				<!-- <el-col :sm="10" :md="10" :lg="10">
                    <el-card class="box-card"  shadow="never" style="height: 224px;text-align: right;">
                        <div style="margin-bottom: 40px;margin-top: 40px;">
                            设备重启将导致自动备份功能短时间失效
                        </div>
                        <el-button  type="primary">获取维护申请码</el-button>
                        <el-button  type="primary">开启维护</el-button>
                        <el-button  type="primary" @click="operationClick(1)">重启设备</el-button>
                        <el-button  type="primary" @click="operationClick(2)">安全关机</el-button>
                    </el-card>
                </el-col> -->

				<el-col :sm="14" :md="14" :lg="14">

				</el-col>
			</el-row>
			<el-row :gutter="10">
				<el-col :sm="12" :md="12" :lg="12">
					<el-card class="box-card" shadow="never" style="height: 310px;">
						<div slot="header" class="clearfix">
							<span class="title">系统时间</span>
							<!-- <el-button style="float: right; " type="primary" @click="timeClick(1)">保存设置</el-button> -->
						</div>
						<div style="margin-bottom:40px">
							<el-form :model="timeForm" ref="timeForm" label-width="30%">
								<el-row :gutter="24">
									<el-col :sm="24" :md="24" :lg="24">
										<el-form-item label="日期：">
											<el-date-picker style="width: 60% !important;" size="small" v-model="timeForm.Date" type="date"
												value-format="yyyy-MM-dd" format="yyyy-MM-dd" placeholder="选择日期"></el-date-picker>
										</el-form-item>
									</el-col>
									<el-col :sm="24" :md="24" :lg="24">
										<el-form-item label="时间：">
											<el-time-picker style="width: 60% !important;" size="small" value-format="HH:mm:ss"
												format="HH:mm:ss" v-model="timeForm.Time" placeholder="请选择时间"></el-time-picker>
										</el-form-item>
									</el-col>
									<!-- <el-col :sm="24" :md="24" :lg="24">
										<el-form-item  label="时区：">
												<el-select size="small" v-model="timeForm.TimeZone" placeholder="请选择时区">
														<el-option label="(UTC+12)新西兰、奥克兰、惠灵顿、斐济、新西兰、瑙鲁" :value="12" />
														<el-option label="(UTC+11)所罗门群岛、库页岛" :value="11" />
														<el-option label="(UTC+10)澳大利亚、海参崴、关岛、堪培拉、墨尔本、悉尼" :value="10" />
														<el-option label="(UTC+09)日本、韩国、东京、首尔、札幌、大阪、东帝汶" :value="9" />
														<el-option label="(UTC+08)中国、马来西亚、菲律宾、新加坡、香港、澳门" :value="8" />
														<el-option label="(UTC+07)泰国、曼谷、河内、雅加达" :value="7" />
														<el-option label="(UTC+06)新西伯利亚、吉尔吉斯斯坦、孟加拉国、不丹" :value="6" />
														<el-option label="(UTC+05)巴基斯坦、土库曼斯坦、马尔代夫" :value="5" />
														<el-option label="(UTC+04)阿布扎比、第比利斯、迪拜、毛里求斯、路易港" :value="4" />
														<el-option label="(UTC+03)非洲东部、俄罗斯、巴格达、科威特、莫斯科、圣彼得堡" :value="3" />
														<el-option label="(UTC+02)欧洲东部、非洲中部、土耳其、以色列、南非" :value="2" />
														<el-option label="(UTC+01)欧洲中部、西非、中非西部、德国、意大利、法国、马德里、西班牙" :value="1" />
														<el-option label="(UTC/GMT)协调世界时、格林威治时间、英国、里斯本、托尔斯港" :value="0" />
														<el-option label="(UTC-01)佛得角、亚速尔群岛" :value="-1" />
														<el-option label="(UTC-02)南乔治亚岛、费尔南多-迪诺罗尼亚岛" :value="-2" />
														<el-option label="(UTC-03)巴西、圣地亚哥、萨尔瓦多、巴西利亚、乌拉圭、阿根廷、苏里南" :value="-3" />
														<el-option label="(UTC-04)委内瑞拉、玻利维亚、巴拉圭、智利" :value="-4" />
														<el-option label="(UTC-05)东部时间(美国和加拿大)、厄瓜多尔、秘鲁、古巴" :value="-5" />
														<el-option label="(UTC-06)美国和加拿大中部时间、蒙特雷、休斯顿、孟菲斯" :value="-6" />
														<el-option label="(UTC-07)山地时间、亚利桑那、马萨特兰、凤凰城、盐湖城、丹佛、埃德蒙顿" :value="-7" />
														<el-option label="(UTC-08)太平洋时间、洛杉矶、旧金山、温哥华、西雅图、拉斯维加斯" :value="-8" />
														<el-option label="(UTC-09)阿拉斯加" :value="-9" />
														<el-option label="(UTC-10)夏威夷" :value="-10" />
														<el-option label="(UTC-11)萨摩亚、纽埃岛" :value="-11" />
														<el-option label="(UTC-12)国际日期变更线以西" :value="-12" />
												</el-select>
										</el-form-item>
								</el-col> -->
								</el-row>
							</el-form>
						</div>
						<div style="width: 100%;margin-top:10px;text-align: right;">
							<el-tooltip class="item" effect="dark" content="刷新时间" placement="top">
								<svg-icon icon-class="刷新时间" @click="timeClick(2)"
									style="font-size: 30px;margin-right:10px;cursor: pointer;" />
							</el-tooltip>
							<el-tooltip class="item" effect="dark" content="设置时间" placement="top">
								<svg-icon icon-class="设置时间" @click="timeClick(1)"
									style="font-size: 30px;margin-right:10px;cursor: pointer;" />
							</el-tooltip>
							<el-tooltip class="item" effect="dark" content="同步时间" placement="top">
								<svg-icon icon-class="同步时间" @click="timeClick(3)" style="font-size: 30px;cursor: pointer;" />
							</el-tooltip>
						</div>

						<!-- <el-button style="float: right; " type="primary" @click="timeClick(3)">同步时间</el-button>
						<el-button style="float: right;margin-right: 10px; " type="primary" @click="timeClick(1)">设置时间</el-button>
						<el-button style="float: right;margin-right: 10px; " type="primary" @click="timeClick(2)">刷新时间</el-button> -->
					</el-card>
				</el-col>

				<el-col :sm="12" :md="12" :lg="12">
					<el-card class="box-card" shadow="never" style="height: 310px;position: relative;">
						<div slot="header" class="clearfix">
							<span class="title">时间同步</span>
							<!-- <el-button style="float: right; " type="primary" @click="confirmClick('syncForm')">保存设置</el-button> -->
						</div>
						<div>
							<el-form :model="syncForm" :rules="rules" ref="syncForm" label-width="30%">
								<el-row :gutter="24">
									<el-col :sm="24" :md="24" :lg="24">
										<el-form-item label="时间同步：" prop="NtpState">
											<el-switch v-model="syncForm.NtpState" :active-value="1" @change='stateClick'
												:inactive-value="0"></el-switch>
										</el-form-item>
									</el-col>
									<el-col :sm="24" :md="24" :lg="24">
										<el-form-item label="NTP服务器：" prop="NtpServer" v-if='syncForm.NtpState === 1'>
											<!-- <el-input maxlength="64" size="small" style="width: 60% !important;" v-model="syncForm.NtpServer" placeholder="请输入NTP服务器" :disabled="syncForm.NtpState===0"></el-input>   -->
											<el-select maxlength="64" size="small" style="width: 60% !important;"
												:disabled="syncForm.NtpState === 0" v-model="syncForm.NtpServer" filterable allow-create
												default-first-option @blur="selectBlur($event)" placeholder="请选择NTP服务器">
												<el-option label="ntp.ntsc.ac.cn" value="ntp.ntsc.ac.cn">
													<span style="float: left">ntp.ntsc.ac.cn</span>
													<span style="float: right; color: #8492a6; font-size: 13px">国家授时中心 NTP
														服务器</span>
												</el-option>
												<el-option label="cn.ntp.org.cn" value="cn.ntp.org.cn">
													<span style="float: left">cn.ntp.org.cn</span>
													<span style="float: right; color: #8492a6; font-size: 13px">中国 NTP
														快速授时服务</span>
												</el-option>
												<el-option label="edu.ntp.org.cn" value="edu.ntp.org.cn">
													<span style="float: left">edu.ntp.org.cn</span>
													<span style="float: right; color: #8492a6; font-size: 13px">教育网</span>
												</el-option>
												<el-option label="ntp.aliyun.com" value="ntp.aliyun.com">
													<span style="float: left">ntp.aliyun.com</span>
													<span style="float: right; color: #8492a6; font-size: 13px">阿里云公共 NTP
														服务器</span>
												</el-option>
												<el-option label="ntp.tencent.com" value="ntp.tencent.com">
													<span style="float: left">ntp.tencent.com</span>
													<span style="float: right; color: #8492a6; font-size: 13px">腾讯云公共 NTP
														服务器</span>
												</el-option>
												<el-option label="hk.ntp.org.cn" value="hk.ntp.org.cn">
													<span style="float: left">hk.ntp.org.cn</span>
													<span style="float: right; color: #8492a6; font-size: 13px">香港地区</span>
												</el-option>
												<el-option label="tw.ntp.org.cn" value="tw.ntp.org.cn">
													<span style="float: left">tw.ntp.org.cn</span>
													<span style="float: right; color: #8492a6; font-size: 13px">台湾地区</span>
												</el-option>
											</el-select>
										</el-form-item>
									</el-col>
									<el-col :sm="24" :md="24" :lg="24">
										<el-form-item label="同步周期：" prop="NtpInterval" v-if='syncForm.NtpState === 1'>
											<el-input maxlength="6" oninput="value=value.replace(/[^0-9]/g,'')" style="width: 60% !important;"
												:disabled="syncForm.NtpState === 0" @mousewheel.native.prevent size="small"
												v-model.number="syncForm.NtpInterval" placeholder="请输入同步周期"><span
													slot="append">分</span></el-input>
										</el-form-item>
									</el-col>
								</el-row>
							</el-form>
						</div>
						<div style="float:right;position: absolute;bottom: 48px;right: 30px;">
							<el-tooltip class="item" effect="dark" content="保存设置" placement="top">
								<svg-icon icon-class="保存设置" @click="confirmClick('syncForm')"
									style="font-size: 30px;cursor: pointer;" />
							</el-tooltip>
						</div>
					</el-card>
				</el-col>
				<el-col :sm="12" :md="12" :lg="12">
					<el-card class="box-card" shadow="never" style="width: 100%;position: relative;">
						<div slot="header" class="clearfix">
							<span class="title">集中管理中心</span>
						</div>
						<div style="margin-bottom: 40px;">
							<el-form label-width="180px" :model="ruleForm" ref="ruleForm" :rules="centerRules"
								style="display: flex;align-items: center;">
								<el-col :sm="24" :md="24" :lg="24">
									<el-form-item label="集中管理中心地址：" prop="center_host">
										<el-input maxlength="128" style="width: 300px !important;" v-model="ruleForm.center_host"
											placeholder="请输入集中管理中心地址"></el-input>
									</el-form-item>
									<el-form-item label="集中管理中心端口号：" prop="center_port">
										<el-input style="width: 300px !important;" oninput="value=value.replace(/[^0-9]/g,'')" maxlength="5"
											v-model.number="ruleForm.center_port" placeholder="请输入端口号">
										</el-input>
									</el-form-item>
									<el-form-item label="数据传输：" prop="is_restful_api_compress">
										<el-radio-group v-model="ruleForm.is_restful_api_compress">
											<el-radio :label="0">压缩</el-radio>
											<el-radio :label="1">普通</el-radio>
										</el-radio-group>
									</el-form-item>
									<el-form-item label="网络检测：" prop="check_net_status_interval">
										<el-input style="width: 300px !important;" placeholder="请输入网络检测间隔"
											oninput="value=value.replace(/[^0-9]/g,'')" maxlength="9"
											v-model.number="ruleForm.check_net_status_interval"><span slot="append">秒</span>
										</el-input>
									</el-form-item>
									<el-form-item label="同步中心配置数据：" prop="is_sync_param_from_center">
										<el-radio-group v-model="ruleForm.is_sync_param_from_center">
											<el-radio :label="0">不同步</el-radio>
											<el-radio :label="1">同步</el-radio>
										</el-radio-group>
									</el-form-item>
									<el-form-item label="心跳间隔：" prop="center_echo_interval">
										<el-input style="width: 300px !important;" placeholder="请输入心跳间隔"
											oninput="value=value.replace(/[^0-9]/g,'')" maxlength="9"
											v-model.number="ruleForm.center_echo_interval"><span slot="append">秒</span>
										</el-input>
									</el-form-item>
									<div style="float:right;position: absolute;bottom: 48px;right: 30px;">
										<el-tooltip class="item" effect="dark" content="保存设置" placement="top">
											<svg-icon icon-class="保存设置" @click="confirmClick('ruleForm')"
												style="font-size: 30px;cursor: pointer;" />
										</el-tooltip>
									</div>
								</el-col>
							</el-form>
						</div>
					</el-card>
				</el-col>
			</el-row>
		</div>
	</div>
</template>

<script>
import { connrequest } from '@/api/firstPage';
import { Upgrade, } from '@/api/firstPage';
import { ipv6Regex, ipv4Regex, hostNameRegex } from '@/utils/RegularExpression.js';
import { parseTime, formatBytes } from '@/utils/index.js';
import { getToken } from '@/utils/auth'
import elDragDialog from '@/directive/el-drag-dialog' // base on element-ui
export default {
	directives: { elDragDialog },
	components: {
	},
	data() {
		var validateSpace = (rule, value, callback) => {
			if ((ipv6Regex.test(value) || ipv4Regex.test(value)) || hostNameRegex.test(value)) {
				callback()
			} else if ((value === '' || value === undefined)) {
				callback(new Error('地址不能为空'))
			} else {
				callback(new Error('请输入正确的NTP服务器地址'))
			}
		}
		return {
			slectIndex: 0,
			selectType: '',
			activeName: 'upgrade',
			radio: 1,
			radio2: 1,
			FileName: '',
			file: [],
			input1: '',
			input2: '',
			checked: true,
			dialogVisible: false,
			DeviceUUID: '',
			tableData: [],
			ruleForm: {},
			fileList: [],
			timeForm: { //系统时间表单
				Date: '',
				Time: '',
				TimeZone: 8 //默认时区北京时间
			},
			syncForm: { // 时间同步表单
				NtpState: 0, //时间同步
				NtpServer: '', //NTP服务器
				NtpInterval: '' //同步周期
			},
			rules: {
				NtpState: { required: false, message: '', trigger: 'change' },
				NtpServer: { required: true, validator: validateSpace, trigger: 'change' },
				NtpInterval: { required: true, message: '请输入同步周期', trigger: 'blur' },
			},
			centerRules: {
				center_host: [
					{ required: true, message: '请输入中心地址', trigger: 'blur' },
					{
						pattern: /^(https?:\/\/)?([a-zA-Z0-9.-]+)(:[0-9]+)?$/,
						message: '请输入合法的地址，例如 127.0.0.1 或 example.com',
						trigger: 'blur'
					}
				],
				center_port: [
					{ required: true, message: '请输入端口号', trigger: 'blur' },
					{
						pattern: /^([1-9][0-9]{0,4})$/,
						message: '请输入 1-65535 之间的端口号',
						trigger: 'blur'
					}
				],
				check_net_status_interval: [
					{ required: true, message: '请输入网络检测间隔', trigger: 'blur' },
					{
						pattern: /^[1-9][0-9]*$/,
						message: '请输入大于 0 的整数',
						trigger: 'blur'
					}
				],
				center_echo_interval: [
					{ required: true, message: '请输入心跳间隔', trigger: 'blur' },
					{
						pattern: /^[1-9][0-9]*$/,
						message: '请输入大于 0 的整数',
						trigger: 'blur'
					}
				]
			},
		}
	},
	created() {
		this.getDataTime();
		this.getTime();
		this.getFileName()
		this.GetThresholdConfig();
	},
	watch: {

	},
	methods: {
		parseTime,
		formatBytes,
		selectBlur(e) {
			if (e.target.value) {
				this.$set(this.syncForm, 'NtpServer', e.target.value);
			}
		},
		copy() {
			const input = this.$refs.inputRef;
			// 判断输入框是否有值
			if (!input || !input.value || input.value.trim() === '') {
				this.$message.warning('复制内容为空');
				return;
			}
			// 选择输入框中的内容
			input.select();
			// 复制选定的文本到剪贴板
			const success = document.execCommand('copy');
			// 取消选择文本
			window.getSelection().removeAllRanges();
			if (success) {
				this.$message.success('复制成功');
			} else {
				this.$message.error('复制失败');
			}
		},
		// 获取集中管理数据
		async GetThresholdConfig() {
			const res = await connrequest('GetThresholdConfig');
			if (res.Status.StatusCode !== 0) return;
			const dataList = res.Data || [];
			this.oldData = dataList;
			// 将数组转为对象格式：{ Name: Value }
			const rawForm = {};
			dataList.forEach(item => {
				rawForm[item.Name] = item.Value;
			});
			// 需要进行单位转换的字段（从秒 → 分钟、天）
			const unitDivideMap = {
				reset_keep_run_seconds: 24 * 3600, // 秒 → 天
				no_agent_offline_timeout: 60,      // 秒 → 分钟
				center_sync_param_interval: 60,    // 秒 → 分钟
				ui_logout_interval: 60             // 秒 → 分钟
			};
			// 构建最终用于表单显示的 ruleForm
			this.ruleForm = Object.keys(rawForm).reduce((acc, key) => {
				const value = rawForm[key];
				// 若该字段需要单位转换，则执行除法，否则直接赋值
				acc[key] = unitDivideMap[key] ? value / unitDivideMap[key] : value;
				return acc;
			}, {});
		},
		// 获取客户端安装包文件名
		async getFileName() {
			const data = {
				Filter: {
					FileName: 'Download.json'
				}
			}
			const res = await connrequest('GetUICommonParam', data)
			this.FileName = res.Data.EDAMPClient
		},
		// 获取客户端日志列表
		async openClientLogs() {
			const res = await connrequest('GetClientLogFile')
			this.tableData = res.Data
			this.dialogVisible = true
		},
		async DeviceUUIDChange() {
			const data = {
				Filter: {
					DeviceUUID: this.DeviceUUID
				}
			}
			const res = await connrequest('GetClientLogFile', data)
			this.tableData = res.Data
		},
		// 客户端日志下载
		async tableDownloadClick(row) {
			try {
				// 确保必要的数据存在
				if (!row.FileName) {
					this.$message.error('文件信息不完整，无法下载');
					return;
				}
				// 构造下载链接，添加时间戳
				const downloadUrl = `${process.env.VUE_APP_BASE_API}/client_log/${row.FileName}?t=${Date.now()}`;
				// 使用 fetch 获取文件流
				const response = await fetch(downloadUrl, {
					method: 'GET',
					headers: {
						'Cache-Control': 'no-cache' // 避免缓存
					}
				});
				// 检查响应是否成功
				if (!response.ok) {
					throw new Error(`下载失败，状态码: ${response.status}`);
				}
				// 获取文件流并转为 Blob
				const blob = await response.blob();
				// 创建临时 URL 并触发下载
				const url = window.URL.createObjectURL(blob);
				const a = document.createElement('a');
				a.style.display = 'none';
				a.href = url;
				a.download = row.FileName.replace(/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}_/, '');
				document.body.appendChild(a);
				a.click();
				// 清理
				document.body.removeChild(a);
				window.URL.revokeObjectURL(url);
			} catch (error) {
				this.$message.error('下载失败，请检查网络或稍后重试');
			}
		},
		// 客户端日志删除
		async tableDeleteClick(row) {
			this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
				confirmButtonText: '确定',
				cancelButtonText: '取消',
				type: 'warning'
			}).then(async () => {
				const data = {
					Filter: {
						FileName: row.FileName
					}
				}
				const res = await connrequest('DelClientLogFile', data)
				if (res.Status.StatusCode === 0) {
					this.$message({
						type: 'success',
						message: '删除成功!'
					});
					this.openClientLogs()
				}
			}).catch(() => {
				this.$message({
					type: 'info',
					message: '已取消删除'
				});
			});
		},
		// 获取时间同步表单数据
		async getDataTime() {
			const res = await connrequest('GetNtpConfig');
			if (res.Status.StatusCode === 0) {
				this.syncForm = res.Data
			}
		},
		// 获取系统时间表单数据
		async getTime() {
			const res = await connrequest('GetSystemTimeAndZone');
			if (res.Status.StatusCode === 0) {
				this.timeForm = res.Data
			}
		},
		// 提交时间同步
		async confirmClick(formName) {
			this.$refs[formName].validate(async (valid) => {
				if (valid) {
					const paramData = {
						Data: this.syncForm,
					};
					const res = await connrequest('SetNtpConfig', paramData);
					if (res.Status.StatusCode === 0) {
						this.$message.success('更改成功');
					}
				} else {
					return false;
				}
			});
		},
		async ApplySSHMaint() {
			const res = await connrequest('ApplySSHMaint');
			if (res.Status.StatusCode === 0) {
				this.input1 = res.Data.ApplyCode;
			}
		},
		async StartSSHMaint() {
			const paramData = {
				Data: {
					ApplyCode: this.input2
				},
			};
			const res = await connrequest('StartSSHMaint', paramData);
			if (res.Status.StatusCode === 0) {
				// this.input1 = res.Data.ApplyCode;
				this.$message.success('维护码识别成功，开始维护');
			}
		},
		async StopSSHMaint() {
			const res = await connrequest('StopSSHMaint');
			if (res.Status.StatusCode === 0) {
				// this.input1 = res.Data.ApplyCode;
				this.$message.success('已结束维护');
			}
		},
		// 修改系统时间配置
		async timeClick(status) {
			if (status === 1) {
				const paramData = {
					Data: this.timeForm,
				};
				const res = await connrequest('SetSystemTimeAndZone', paramData);
				if (res.Status.StatusCode === 0) {
					// 成功将返回值存进store里面，用于实时同步顶部导航栏时间
					this.$store.commit('user/SET_DATETIME', this.timeForm.Date + ' ' + this.timeForm.Time);
					this.$message.success('更改成功');
					this.getTime();
				}
			} else if (status === 2) {
				await this.getTime();
				this.$message.success('刷新时间成功');
			} else if (status === 3) {
				let currentDate = new Date();
				let year = currentDate.getFullYear().toString();
				let month = ('0' + (currentDate.getMonth() + 1)).slice(-2);  // 补零操作，确保两位数表示月份
				let day = ('0' + currentDate.getDate()).slice(-2);  // 补零操作，确保两位数表示日期
				let hours = ('0' + currentDate.getHours()).slice(-2);  // 补零操作，确保两位数表示小时
				let minutes = ('0' + currentDate.getMinutes()).slice(-2);  // 补零操作，确保两位数表示分钟
				let seconds = ('0' + currentDate.getSeconds()).slice(-2);  // 补零操作，确保两位数表示秒数
				let formattedDate = year + "-" + month + "-" + day;
				let formattedTime = hours + ":" + minutes + ":" + seconds;
				this.$set(this.timeForm, 'Date', formattedDate)
				this.$set(this.timeForm, 'Time', formattedTime)
				const paramData = {
					Data: this.timeForm,
				};
				const res = await connrequest('SetSystemTimeAndZone', paramData);
				if (res.Status.StatusCode === 0) {
					this.$message.success('刷新时间成功');
					this.getTime();
				}
			}
		},
		// 数据服务中心状态切换判断
		stateClick(val) {
			// 值为0时初始化表单
			if (val === 0) {
				this.$nextTick(() => {
					this.$refs["syncForm"].clearValidate();
				});
			}
		},
		upgradeClick(file) {
			// 系统升级
			const loading = this.$loading({
				lock: true,
				text: '系统升级中请稍后......',
				spinner: 'el-icon-loading',
				background: 'rgba(0, 0, 0, 0.7)'
			});

			if (file.file.size > 536870912) {
				this.$refs['uploads' + this.slectIndex].clearFiles();
				setTimeout(() => {
					loading.close();
					this.$message.warning('文件大小不允许超过512M');
				}, 1000)

			} else {
				let formData = new FormData();
				if (this.selectType === '安全规则库') {
					formData.append('CmdCode', "UpgradeSignature");
					formData.append('file', file.file);
					Upgrade(formData).then((res) => {
						if (res.Status.StatusCode === 0) {
							loading.close();
							this.$message.success('升级成功');
							this.$refs['uploads' + this.slectIndex].clearFiles();
						} else {
							this.$message.error(res.Status.Msg2Client)
						}
					}).catch(() => {
						this.$message.error('请求错误')
						this.$refs['uploads' + this.slectIndex].clearFiles();
						setTimeout(() => {
							loading.close();
						}, 1000)
					});
				} else if (this.selectType === '病毒库') {
					formData.append('CmdCode', "UpgradeVirus");
					formData.append('file', file.file);
					formData.append('Token', JSON.stringify(getToken()))
					Upgrade(formData).then(() => {
						if (res.Status.StatusCode === 0) {
							loading.close();
							this.$message.success('升级成功');
							this.$refs['uploads' + this.slectIndex].clearFiles();
						} else {
							this.$message.error(res.Status.Msg2Client)
						}
					}).catch(() => {
						this.$message.error('请求错误')
						this.$refs['uploads' + this.slectIndex].clearFiles();
						setTimeout(() => {
							loading.close();
						}, 1000)
					});
				} else {
					formData.append('CmdCode', "Upgrade");
					formData.append('file', file.file);
					Upgrade(formData).then((res) => {
						if (res.Status.StatusCode === 0) {
							loading.close();
							this.$message.success('升级成功');
							this.$refs['uploads' + this.slectIndex].clearFiles();
						} else {
							this.$message.error(res.Status.Msg2Client)
						}
					}).catch((res) => {
						this.$message.error('请求错误')
						this.$refs['uploads' + this.slectIndex].clearFiles();
						setTimeout(() => {
							loading.close();
						}, 1000)

					});
				}

			}

		},
		async downloadTool(name) {
			const loadingInstance = this.$loading({
				lock: true, // 锁定屏幕，防止用户操作
				text: '文件下载中，请稍候...', // 提示文字
				spinner: 'el-icon-loading', // 加载图标
				background: 'rgba(0, 0, 0, 0.7)', // 背景遮罩
			});
			try {
				// 构造下载链接，添加时间戳
				const downloadUrl = `${window.location.origin}/${name}?t=${Date.now()}`;
				// 使用 fetch 获取文件流
				const response = await fetch(downloadUrl, {
					method: 'GET',
					headers: {
						'Cache-Control': 'no-cache' // 避免缓存
					}
				});
				// 检查响应是否成功
				if (!response.ok) {
					throw new Error(`下载失败，状态码: ${response.status}`);
				}
				// 获取文件流并转为 Blob
				const blob = await response.blob();
				// 创建临时 URL 并触发下载
				const url = window.URL.createObjectURL(blob);
				const a = document.createElement('a');
				a.style.display = 'none';
				a.href = url;
				a.download = name;
				document.body.appendChild(a);
				a.click();
				// 清理
				document.body.removeChild(a);
				window.URL.revokeObjectURL(url);
			} catch (error) {
				this.$message.error('下载失败，请检查网络或稍后重试');
			} finally {
				// 无论成功或失败，关闭 Loading
				loadingInstance.close();
			}
		},
		// 重启和关机
		async operationClick(row) {
			if (row === 1) {
				this.$confirm('是否重启系统？重启将导致桌面管理系统短时间失效。', '提示', {
					confirmButtonText: '确定',
					cancelButtonText: '取消',
					type: 'warning'
				}).then(async () => {
					const res = await connrequest('RebootSystem');
					if (res.Status.StatusCode === 0) {
						this.$message({
							type: 'success',
							message: '系统重启成功!'
						});
						await this.$store.dispatch('user/logout')
						this.$router.push(`/login?`)
					}
				}).catch(() => {
					this.$message({
						type: 'info',
						message: '已取消重启'
					});
				});
			} else {
				this.$confirm('是否将系统关机?', '提示', {
					confirmButtonText: '确定',
					cancelButtonText: '取消',
					type: 'warning'
				}).then(async () => {
					const res = await connrequest('PoweroffSystem');
					if (res.Status.StatusCode === 0) {
						this.$message({
							type: 'success',
							message: '关机成功!'
						});
						await this.$store.dispatch('user/logout')
						this.$router.push(`/login?`)
					}
				}).catch(() => {
					this.$message({
						type: 'info',
						message: '已取消关机'
					});
				});
			}
		},
		async recoverClick(status) {
			if (status === 1) {
				const res = await connrequest('ExportProjectBackupFile');
				if(res.Status.StatusCode === 0){
					this.downloadTool('config_bak/config.tgz')
				}
				
			} else if (status === 2) {
				const loading = this.$loading({
					lock: true,
					text: '恢复系统配置中请稍后......',
					spinner: 'el-icon-loading',
					background: 'rgba(0, 0, 0, 0.7)'
				});
				if (this.file.size > 536870912) {
					setTimeout(() => {
						loading.close();
						this.$message.warning('文件大小不允许超过512M');
					}, 1000)
				} else {
					let formData = new FormData();
					formData.append('CmdCode', "ImportProjectBackupFile");
					formData.append('FileName', 'config.tgz');
					formData.append('Token', JSON.stringify(getToken()));
					formData.append('file', this.file);
					Upgrade(formData).then(() => {
						// if (res.Status.StatusCode===0) {
						this.$refs['upload'].clearFiles();
						this.fileList = []
						loading.close();
						this.$message.success('恢复系统配置成功');
						// this.$refs.uploads.clearFiles();
						// }
					}).catch(() => {
						this.$refs['upload'].clearFiles();
						this.fileList = []
						setTimeout(() => {
							loading.close();
						}, 1000)
						// this.$refs.uploads.clearFiles();
					});
				}
			} else if (status === 4) {
				if (this.checked) {
					this.$confirm('是否恢复出厂配置并删除数据?', '提示', {
						confirmButtonText: '确定',
						cancelButtonText: '取消',
						type: 'warning'
					}).then(async () => {
						const res = await connrequest('RestoreFactoryAndData');
						if (res.Status.StatusCode === 0) {
							this.$message({
								type: 'success',
								message: '恢复出厂配置并删除数据成功，5 秒后将自动退出登录！'
							});
							// 等待 5 秒后再执行退出登录和跳转
							setTimeout(async () => {
								await this.$store.dispatch('user/logout');
								this.$router.push('/login');
							}, 5000);
						}
					}).catch(() => {
						this.$message({
							type: 'info',
							message: '已取消恢复出厂配置并删除数据'
						});
					});
				} else {
					this.$confirm('是否恢复出厂配置?', '提示', {
						confirmButtonText: '确定',
						cancelButtonText: '取消',
						type: 'warning'
					}).then(async () => {
						const res = await connrequest('RestoreFactoryAndData');
						if (res.Status.StatusCode === 0) {
							this.$message({
								type: 'success',
								message: '恢复出厂配置成功，5 秒后将自动退出登录！'
							});
							// 等待 5 秒后再执行退出登录和跳转
							setTimeout(async () => {
								await this.$store.dispatch('user/logout');
								this.$router.push('/login');
							}, 5000);
						}
					}).catch(() => {
						this.$message({
							type: 'info',
							message: '已取消恢复出厂配置数据'
						});
					});
				}

			}
		},
		// 提交集中管理中心配置
		async confirmClick(formName) {
			this.$refs[formName].validate(async (valid) => {
				if (valid) {
					// 字段中文描述映射（用于构建 Descp 字段）
					const fieldDescpMap = {
						center_host: '集中管理中心地址',
						center_port: '集中管理中心端口号',
						is_restful_api_compress: '数据传输',
						check_net_status_interval: '网络检测间隔',
						center_echo_interval: '心跳间隔',
						is_sync_param_from_center: '同步中心配置数据'
					};
					// 构造最终提交参数数组
					const formArray = Object.keys(this.ruleForm).map(key => {
						// 原始值
						const rawValue = this.ruleForm[key];
						// 获取字段描述，优先取固定映射，没有则从 oldData 中找
						const descp = fieldDescpMap[key] || this.oldData?.find(item => item.Name === key)?.Descp || '';
						return {
							Name: key,
							Value: rawValue,
							Descp: descp
						};
					});
					
					const paramData = {
						Data: formArray,
					};
					const res = await connrequest('SetThresholdConfig', paramData);
					if (res.Status.StatusCode === 0) {
						this.$message.success('更改成功');
						this.GetThresholdConfig();
					}
				} else {
					return false;
				}
			});
		},
		handleChange(row) {
		},
		handleRemove(file, fileList) {
			if (fileList.length === 0) {
				file.name = '';
			}
		},

		handlePreview(file, fileList) {
		},
		onChange(file, fileList) {
			this.file = file.raw;
			this.recoverClick(2)
			// this.DataRecover.File = file.name;
		},
		handleExceed(files, fileList) {
			this.$message.warning(`当前限制选择 1 个文件，本次选择了 ${files.length} 个文件，共选择了 ${files.length + fileList.length} 个文件`);
		},
		handleExceeds(files, fileList) {
			this.$message.warning(`当前限制选择 1 个文件，本次选择了 ${files.length} 个文件，共选择了 ${files.length + fileList.length} 个文件`);
		},
		beforeRemove(file, fileList) {
			return this.$confirm(`确定移除 ${file.name}？`);
		},
		checkBeforeClick(e) {
      if (this.$isFromCenter) {
        e.stopPropagation(); // 阻止 el-upload 弹出选择框
        this.$message.error('当前模式不支持系统升级')
        return
      }
    },
		checkBeforeClick2(e) {
      if (this.$isFromCenter) {
        e.stopPropagation(); // 阻止 el-upload 弹出选择框
        this.$message.error('当前模式不支持配置恢复')
        return
      }
    },
	}
}
</script>

<style lang='scss' scoped>
// 将设备维护板块的按钮对齐
.el-button+.el-button,
.el-checkbox.is-bordered+.el-checkbox.is-bordered {
	margin-left: 3px;
}

::v-deep.el-card__header {
	padding: 10px !important;
}

.box-card {
	// margin: 16px;
	margin-bottom: 10px !important;
}

.radioClass {
	.el-radio {
		line-height: 35px;
		height: 35px;
		display: block;
		overflow: auto;
		// margin-bottom: 15px;
	}

	// height: 100px;
	// display: flex;
}
</style>